/* global  expect, apiTest */

require('../../apiTest')
const Role = {}

// 权限列表
Role.powers = [
  'app',
  'appList',
  'appCreate',
  'appEnable',
  'appEdit',
  'appPush',
  'appApi',
  'staffList',
  'power',
  'admin',
  'adminShow',
  'adminCreate',
  'adminEdit',
  'adminPower',
  'adminRemove',
  'role',
  'roleCreate',
  'roleEdit',
  'roleRemove',
  'log',
  'logLogin',
  'logAdmin',
  'logPush',
  'logApi'
]

// 列表单条验证
Role.checkOne = function(v, post) {
  expect(v).to.be.an('object')
  apiTest.isObjectId(v._id)
  expect(v.name).to.be.an('string')
  if (v.mark) expect(v.mark).to.be.an('string')
  if (v.powers) expect(v.powers).to.be.an('array')
  if (post) {
    if (post.name) expect(v.name).to.equal(post.name)
    if (post.mark) expect(v.mark).to.equal(post.mark)
    if (post.powers) expect(v.powers).to.deep.equal(post.powers)
  }
}

// 列表通用验证
Role.checkList = function(get, cb) {
  return apiTest.get('/role/find', Object.assign({}, get))
    .then(function(res) {
      var data = apiTest.apiOk(res)
      expect(data).to.be.a('object')
      // 验证分页
      apiTest.checkPaging(data)
      data.list.forEach(function(v) {
        Role.checkOne(v)
        if (cb) cb(v)
      })
    })
}
// 生成随机提交数据
Role.randOne = function() {
  return {
    name: 'autoTest' + (new Date()).getTime(),
    powers: apiTest.ranArr(Role.powers, 0, 10)
  }
}

// 删除角色
Role.removeOne = function(_id, cb) {
  return apiTest.post('/role/remove', { _id: _id }).then(function(res) {
    var data = apiTest.apiOk(res)
    expect(data.ok).to.equal(1)
    expect(data.n).to.equal(1)
    if (cb) return cb()
  })
}
// 修改并查询验证
Role.editOne = function(_id, post, cb) {
  post._id = _id
  return apiTest.post('/role/update?_id=' + _id, post).then(function(res) {
    apiTest.apiOk(res)
    // 查
    return apiTest.get('/role/findOne', { _id: _id }).then(function(res) {
      var data = apiTest.apiOk(res)
      Role.checkOne(data, post)
      if (cb) return cb(data)
    })
  })
}

// 添加
Role.addOne = function(post, cb) {
  return apiTest.post('/role/create', post).then(function(res) {
    var data = apiTest.apiOk(res)
    Role.checkOne(data, post)
    if (cb) return cb(data)
  })
}

module.exports = Role
